﻿/**
 *
 *
 * Created by tianye on 2015/7/25.
 */
var cookieOptions = {};
cookieOptions.path = "/";
cookieOptions.expires = 365;


function getLucyInfo() {
    //$.ajax({
    //    url: "/lucy_info.json",
    //    type: "get",
    //    contentType: "application/json",
    //    dataType: "json",
    //    async:false,
    //    success: function (data) {//ajax返回的数据
    //        $.cookie("lucy.host", data.host,cookieOptions);
    //        $.cookie("lucy.https.port", data.https_port,cookieOptions);
    //        $.cookie("lucy.http.port", data.http_port,cookieOptions);
    //    }
    //});

    if (window.location.hostname == 'localhost') {
        $.cookie("lucy.host", 'localhost');
        $.cookie("lucy.https.port", 8457);
        $.cookie("lucy.http.port", 8088);
    }else if (window.location.hostname == '172.28.6.41') {
        $.cookie("lucy.host", '172.28.6.41');
        $.cookie("lucy.https.port", 8457);
        $.cookie("lucy.http.port", 8088);
    } else if (window.location.hostname == '10.58.100.35') {
        $.cookie("lucy.host", '10.58.100.35');
        $.cookie("lucy.https.port", 8457);
        $.cookie("lucy.http.port", 8088);
    }else if (window.location.hostname == '10.10.10.64') {
        $.cookie("lucy.host", '10.10.10.31');
        $.cookie("lucy.https.port", 8457);
        $.cookie("lucy.http.port", 8097);
    } else if (window.location.hostname == '10.10.10.33') {
        $.cookie("lucy.host", '10.10.10.126');
        $.cookie("lucy.https.port", 453);
        $.cookie("lucy.http.port", 8093);
    } else if (window.location.hostname == 'wo-link-test.oss-cn-shenzhen.aliyuncs.com') {
        $.cookie("lucy.host", '10.10.10.126');
        $.cookie("lucy.https.port", 453);
        $.cookie("lucy.http.port", 8093);
    } else if (window.location.hostname == '10.10.10.202') {
        $.cookie("lucy.host", '10.10.10.126');
        $.cookie("lucy.https.port", 8453);
        $.cookie("lucy.http.port", 8093);
    } else if (window.location.hostname == 's3.cn-north-1.amazonaws.com.cn') {
        $.cookie("lucy.host", '10.10.10.126');
        $.cookie("lucy.https.port", 8453);
        $.cookie("lucy.http.port", 8093);
    } else if (window.location.hostname == 'fast-recovery-test.s3-website.cn-north-1.amazonaws.com.cn') {
        $.cookie("lucy.host", '54.223.245.166');
        $.cookie("lucy.https.port", 4443);
        $.cookie("lucy.http.port", 8080);
    } else if (window.location.hostname == '10.10.10.126') {
        $.cookie("lucy.host", '10.10.10.126');
        $.cookie("lucy.https.port", 453);
        $.cookie("lucy.http.port", 8093);
    } else if (window.location.hostname == '120.24.66.250') {
        $.cookie("lucy.host", '120.24.66.250');
        $.cookie("lucy.https.port", 4443);
        $.cookie("lucy.http.port", 8080);
    } else if (window.location.hostname == 'fast-recovery-html-p.s3-website.cn-north-1.amazonaws.com.cn') {
        $.cookie("lucy.host", '54.222.163.153');
        $.cookie("lucy.https.port", 4443);
        $.cookie("lucy.http.port", 8093);
    } else if (window.location.hostname == 'frh160723.s3-website.cn-north-1.amazonaws.com.cn') {
        $.cookie("lucy.host", '54.222.163.153');
        $.cookie("lucy.https.port", 4443);
        $.cookie("lucy.http.port", 8093);
    }
    else if (window.location.hostname == '10.10.10.233') {
        $.cookie("lucy.host", '10.10.10.233');
        $.cookie("lucy.https.port", 8452);
        $.cookie("lucy.http.port", 8092);
    }
    else if (window.location.hostname == '10.10.10.2') {
        $.cookie("lucy.host", '10.10.10.2');
        $.cookie("lucy.https.port", 8451);
        $.cookie("lucy.http.port", 8091);
    }
    else if (window.location.hostname == 'ivylink.xicp.net') {
        $.cookie("lucy.host", 'ivylink.xicp.net');
        $.cookie("lucy.https.port", 453);
        $.cookie("lucy.http.port", 8093);
    } else if (window.location.hostname == 'yy-recovery.s3-website.cn-north-1.amazonaws.com.cn')
    {
        $.cookie("lucy.host", '54.222.163.153');
        $.cookie("lucy.https.port", 4443);
        $.cookie("lucy.http.port", 8093);
    }
    else

    {
        $.cookie("lucy.host", null);
        $.cookie("lucy.https.port", null);
        $.cookie("lucy.http.port", null);
        //alert('环境不存在!');
       // toastr.error('环境不存在!');
    }


}

// getLucyInfo();

function buildUrl(pathname) {
    var host = getCookie("lucy.host");
    console.log(host);
    if (host == null || host == "null") {
        console.log("host is null");
        host = window.location.hostname;
        console.log("host is null,use window.location.hostname:" + host);
    }

    var httpPort = getCookie("lucy.http.port");
    if (httpPort == null || httpPort == "null") {
        httpPort = window.location.port;
    }

    var httpsPort = getCookie("lucy.https.port");
    if (httpsPort == null || httpsPort == "null") {
        httpsPort = window.location.port;
    }
    //return "https://" + host + ":" + httpsPort + pathname;

    if (window.location.protocol == "https:") {
        return "https://" + host + ":" + httpsPort + pathname;
    }
    else {
        return "http://" + host + ":" + httpPort + pathname;
    }


}

function errorAlert(msg) {
    console.log(msg);
}

function warnAlert(msg) {
    console.log(msg);
}

function infoAlert(msg) {
    console.log(msg);
}

function debugAlert(msg) {
    console.log(msg);
}

function doPost(location, dto, success, fail) {
    restful(location, dto, success, fail, "post");
}

function doPut(location, dto, success, fail) {
    restful(location, dto, success, fail, "put");
}

function doGet(location, dto, success, fail) {
    restful(location, dto, success, fail, "get");
}

function doDelete(location, dto, success, fail) {
    restful(location, dto, success, fail, "delete");
}

function doPostSyn(location, dto, success, fail) {
    restfulSyn(location, dto, success, fail, "post");
}

function doPutSyn(location, dto, success, fail) {
    restfulSyn(location, dto, success, fail, "put");
}

function doGetSyn(location, dto, success, fail) {
    restfulSyn(location, dto, success, fail, "get");
}

function doDeleteSyn(location, dto, success, fail) {
    restfulSyn(location, dto, success, fail, "delete");
}
var loadingCount = 0;
var loadingDiv = null;
var maskLoading = null;
function buildLoadingDiv() {
    if (loadingDiv == null) {
        loadingDiv = $('<div id="loading">');
        var subDiv;
        for (var i = 0; i < 5; i++) {
            subDiv = $("<div class='color1'>");
            loadingDiv.append(subDiv);
        }
        for (var j = 0; j < 5; j++) {
            subDiv = $("<div class='color2'>");
            loadingDiv.append(subDiv);
        }
        $(document.body).append(loadingDiv);
    }

    //return loadingDiv;

    if (maskLoading == null) {
        maskLoading = $('<div id="mask-loading">');
        $(document.body).append(maskLoading);
    }
}
var networkErrorAlertTime = 0;
function _restful(async, location, dto, success, fail, method) {
    var dtoObj;
    if (method == "get") {
        dtoObj = dto;
    } else if (method == "post" || method == "put" || method == "delete") {
        dtoObj = JSON.stringify(dto);
    }
    $.ajax({
        url: buildUrl(location),
        data: dtoObj,
        type: method,
        contentType: "application/json",
        dataType: "json",
        traditional: true,
        async: async,
        timeout: 20000,
        beforeSend: function (XHR) {
            loadingCount++;
            //debugAlert("loadingCount add " + loadingCount );
            //buildLoadingDiv();
            //loadingDiv.removeClass("hide");
            //maskLoading.removeClass("hide");
        },
        complete: function (XMLHttpRequest, status) {
            if (--loadingCount == 0) {
                //loadingDiv.addClass("hide");
                //maskLoading.addClass("hide");

                networkErrorAlertTime = 0;
            }

            if (networkErrorAlertTime == 0) {
                if (status == "error") {
                    //alert("请检查是否正确连接到网络！");
                    toastr.error("请检查是否正确连接到网络！");
                    //alert(location);
                    //alert(XMLHttpRequest.responseText);

                    networkErrorAlertTime++;
                }
                if (status == "timeout") {
                    //alert("网络不给力，请稍后再次尝试！");
                    toastr.error("网络不给力，请稍后再次尝试！");
                    networkErrorAlertTime++;
                }
            }
        },
        success: function (data) {
            var resultCode = data.result_code;
            debugAlert(method + " - " + location + " : " + resultCode + " -- " + data.result_msg);
            debugAlert(data);

            if (resultCode == "11720001") {
                //logout(false,false);
                //showLoginDiv();

                window.location.href = "index.html";

                logout();
                return;
            }

            if (resultCode != "0") {
                if (fail != null) {
                    fail(data.result_msg, data.result_code);
                } else {
                    //alert(data.result_msg);
                    toastr.error(data.result_msg);
                }
            } else {
                success(data);
            }
        }
        //error: function(XMLHttpRequest, textStatus, errorThrown) {
        //    alert(location);
        //    alert("status : " + XMLHttpRequest.status);
        //    alert("readyState : " + XMLHttpRequest.readyState);
        //    alert("textStatus : " + textStatus);
        //    alert("responseText : " + XMLHttpRequest.responseText);
        //}
    });
}

//异步发送
function restful(location, dto, success, fail, method) {
    _restful(true, location, dto, success, fail, method);
}

//同步发送
function restfulSyn(location, dto, success, fail, method) {
    _restful(false, location, dto, success, fail, method);
}

function setToken(token) {
    setCookie("token", token);
}

function addTokenToDTO(dto) {
    var token = getCookie("token");
    if (token == 'null' || token == null || token == "") {
        window.location.href = "index.html";
        return false;
        //window.location.href = "/index.html?url="+window.location.pathname+window.location.search;
        //return false;
    } else {
        dto.token = token;
        return true;
    }
}

function hasToken() {
    var token = getCookie("token");
    if (token == 'null' || token == null || token == "") {
        return false;
    } else {
        return true;
    }
}

function assertTokenNotNull() {
    var token = getCookie("token");
    console.log("token" + token);
    if (token == 'null' || token == null || token == "") {
        window.location.href = "/index.html?url=" + window.location.pathname + window.location.search;
    }
}

function logout(is_refresh, goback) {
    var tokenDTO = {};
    addTokenToDTO(tokenDTO);
    setCookie("token", null);
    setCookie("im_patient_account", null);
    setCookie("im_patient_pwd", null);
    setCookie("im_medical_staff_id", null);
    setCookie("im_doctor_account", null);
    setCookie("im_doctor_pwd", null);
    setCookie("im_name", null);
    setCookie("hospital_id", null);
    setCookie("division_id", null);
    //setCookie("mobile", null);

    localStorage.clear();
    sessionStorage.clear();

    deviceLogout();
    $.ajax({
        url: buildUrl("/victoria/token.json"),
        dataType: "json",
        contentType: "application/json",
        data: JSON.stringify(tokenDTO),
        type: "delete",
        success: function (data) {
            if ("0" == data.result_code) {
                if (is_refresh) {
                    refresh_page();
                    refreshAllPage();
                }
                if (goback) {
                    goBack();
                    refreshAllPage();
                }

                //

                //var refresh = 1 + (1 << 4) + (1 << 8) + (1 << 12);
                //if (activityManager != null) {
                //    //全部刷新
                //    activityManager.injectRefreshWebState(refresh);
                //} else if (iOSActionManager != null) {
                //    //全部刷新
                //    iOSActionManager.injectRefreshWebState(refresh);
                //}
            }
        }
    });
}

String.prototype.startWith = function (str) {
    var reg = new RegExp("^" + str);
    return reg.test(this);
};

String.prototype.endWith = function (str) {
    var reg = new RegExp(str + "$");
    return reg.test(this);
};

String.prototype.replaceAll = function (s1, s2) {
    return this.replace(new RegExp(s1, "gm"), s2);
};


function addParamToUrl(map) {
    var nowUrl = window.location.href;
    var shortUrl = "";
    var params = "";
    var oldParams = [];

    var idx = nowUrl.indexOf("?");
    if (idx > 0) {
        shortUrl = nowUrl.substr(0, idx);
        oldParams = nowUrl.substring(idx + 1, nowUrl.length).split("&");
    } else {
        shortUrl = nowUrl;
    }

    $.each(map, function (key, value) {
        var v = $.getUrlParam(key);

        if (v != null) {
            $.each(oldParams, function (idx, val) {
                if (val.startWith(key + "=")) {
                    oldParams[idx] = '';
                }
            });
        }

        if (params.length > 0) {
            params += "&";
        }
        params += key + "=" + value;
    });

    $.each(oldParams, function (idx, p) {
        if (p != '') {
            if (params.length > 0) {
                params += "&";
            }
            params += p;
        }
    });

    nowUrl = shortUrl + "?" + params;

    window.history.replaceState(null, null, nowUrl);
}

function setParamToUrl(map) {
    var nowUrl = window.location.href;
    var shortUrl = "";
    var params = "";

    var idx = nowUrl.indexOf("?");
    if (idx > 0) {
        shortUrl = nowUrl.substr(0, idx);
        //params = nowUrl.substring(idx + 1, nowUrl.length);
    } else {
        shortUrl = nowUrl;
    }

    $.each(map, function (key, value) {
        if (params.length > 0) {
            params += "&";
        }
        params += key + "=" + value;
    });

    nowUrl = shortUrl + "?" + params;

    window.history.replaceState(null, null, nowUrl);
}
//function alert(content) {
//    if(iOSActionManager != null) {
//        //iOSActionManager.iosAlertShow(content);
//        alert(content);
//
//    } else{
//        alert(content);
//    }
//}
